package org.itboys.core.service.mongo.front;

import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.core.common.ExceptionEnum;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.dto.count.SundayCountDto;
import org.itboys.core.dto.count.SundayCountSceneDto;
import org.itboys.core.dto.scene.SundaySceneDto;
import org.itboys.core.entity.mongo.SundayCart;
import org.itboys.core.entity.mongo.SundayCartGoodsSize;
import org.itboys.core.entity.mongo.SundayScene;
import org.itboys.core.service.mongo.web.SundaySceneService;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 作者：zzq
 * 时间：2018/10/15
 * 描述：购物车
 */
@Service
public class SundayFrontCartService extends BaseMongoService<SundayCart> {
    @Resource(name = "mobileDs")
    private MongoDataSource sundayDataSource;
    @Autowired
    private SundayFrontCartGoodsSizeService sizeService;
    @Autowired
    private SundaySceneService sceneService;
    @Autowired
    private ResourceHolder resourceHolder;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return sundayDataSource;
    }

    @Override
    protected Class<SundayCart> getEntityClass() {
        return SundayCart.class;
    }

    public Long addCart(Long memberId, Long sceneId, Integer num, Integer cartType, List<Double> goodsPrices, List<Integer> goodsNums,
                        List<String> goodsIds, List<String> goodsCodeIds,List<String> goodsCodes) {
        if (ListUtil.isNull(goodsPrices) || ListUtil.isNull(goodsNums) || ListUtil.isNull(goodsIds) || ListUtil.isNull(goodsCodeIds)||ListUtil.isNull(goodsCodes)) {
            throw new ErrorException(ExceptionEnum.ADD_CART_EXCEPTION.getValue());
        }
        Long cartId = 0L;
        List<SundayCart> oldCarts = new ArrayList<>();
        //如果是立即购买加入购物车，先删除原来购物车中立即购买加入的数据
        if (cartType.equals(SundayCommonConstants.cart_type_buy_now)) {
            deleteCart(null, memberId, SundayCommonConstants.cart_type_buy_now);
            //直接加入购物车
        } else if(cartType.equals(SundayCommonConstants.cart_type_send)){
            deleteCart(null, memberId, SundayCommonConstants.cart_type_send);
        } else{
            //原来是否已经加入过购物车存在的数据
            Map<String, Object> param = new HashMap<>();
            param.put("isDeleted", SundayCommonConstants.NO);
            param.put("memberId", memberId);
            param.put("cartType", cartType);
            param.put("sceneId", sceneId);
            oldCarts = super.list(param);
            //判断之前是否有完全相同尺码的购物车
            if(ListUtil.isNotNull(oldCarts)){
                param.clear();
                param.put("isDeleted", SundayCommonConstants.NO);
                param.put("cartId", cartId);
                List<SundayCartGoodsSize> oldSizes = sizeService.list(param);
                int goodsIdLength=0;
                int goodsCodeIdLength=0;
                for (SundayCartGoodsSize size :oldSizes) {
                    for (String goodsId :goodsIds) {
                        if(goodsId.equals(size.getCodeId())){
                            goodsIdLength++;
                            break;
                        }
                    }
                    for (String goodsCodeId :goodsCodeIds) {
                        if(goodsCodeId.equals(size.getCodeId())){
                            goodsCodeIdLength++;
                            break;
                        }
                    }
                }
                if(oldSizes.size()!=goodsIdLength||oldSizes.size()!=goodsCodeIdLength
                        ||goodsIdLength!=goodsIds.size()||goodsCodeIdLength!=goodsCodeIds.size()){
                    oldCarts=new ArrayList<>();
                }
            }

        }
        //如果已经存在，就叠加数量
        if (ListUtil.isNotNull(oldCarts)) {
            super.update(oldCarts.get(0).getId(), "num", num + oldCarts.get(0).getNum());
            cartId = oldCarts.get(0).getId();
            //更新购物车商品尺码数量
            Map<String, Object> param = new HashMap<>();
            param.put("isDeleted", SundayCommonConstants.NO);
            param.put("cartId", cartId);
            List<SundayCartGoodsSize> sizes = sizeService.list(param);
            for (SundayCartGoodsSize size : sizes) {
                Integer sizeNum = size.getNum();
                size.setNum(sizeNum * (num + 1));
                sizeService.updateExceptEmpty(size.getId(), size);
            }
            //如果不存在，就新增
        } else {
            Double scenePrice=0.0;
            for (int i = 0; i < goodsPrices.size(); i++) {
                scenePrice+=goodsPrices.get(i)*goodsNums.get(i);
            }
            SundayCart cart = new SundayCart(memberId, sceneId, num, cartType,scenePrice, SundayCommonConstants.NO);
            super.save(cart);
            //生成购物车商品尺码
            for (int i = 0; i < goodsCodeIds.size(); i++) {
                sizeService.save(new SundayCartGoodsSize(cart.getId(), goodsIds.get(i), goodsCodeIds.get(i),
                        goodsNums.get(i), goodsPrices.get(i),goodsCodes.get(i)));
            }
            cartId = cart.getId();
        }

        return cartId;
    }

    public void updateCart(Long cartId,Integer num,Integer type){
        if(type==0){
            num=-num;
        }
        SundayCart cart = super.getById(cartId);
        if((cart.getNum()+num)<=0){
            throw new ErrorException(ExceptionEnum.CART_NUM_EXCEPTION.getValue());
        }
        //更新购物车商品尺码数量
        Map<String, Object> param = new HashMap<>();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("cartId", cartId);
        List<SundayCartGoodsSize> sizes = sizeService.list(param);
        for (SundayCartGoodsSize size : sizes) {
            Integer sizeNum = size.getNum();
            Integer rate=sizeNum/cart.getNum();
            size.setNum(sizeNum +num*rate);
            sizeService.updateExceptEmpty(size.getId(), size);
        }
        super.update(cartId, "num", num + cart.getNum());

    }

    /**
     * 获取购物车   结算商品信息
     *
     * @param memberId
     * @param cartIds
     * @param cartType
     * @return
     */
    public SundayCountDto getCart(Long memberId, List<Long> cartIds, Integer cartType, Integer status) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("memberId", memberId);
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("status", status);
        if (ListUtil.isNotNull(cartIds)) {
            param.put("id in", cartIds);
        }
        if (cartType != null) {
            param.put("cartType", cartType);
        }
        List<SundayCart> carts = super.list(param);
        SundayCountDto countDto = new SundayCountDto();
        Integer totalNumber = 0;
        countDto.setTotalAmount(0.0);
        countDto.setPayAmount(0.0);
        if (ListUtil.isNull(carts)) {
            return countDto;
        }
        List<Long> sceneIds = carts.stream().map(e -> e.getSceneId()).collect(Collectors.toList());
        param.clear();
        param.put("id in", sceneIds);
        List<SundayScene> scenes = sceneService.list(param);

        //购物车场景
        List<SundayCountSceneDto> countScenes = new ArrayList<SundayCountSceneDto>();
        Double totalAmount = 0.00;
        Double payAmount = 0.00;
        for (SundayScene scene : scenes) {
            //售价
            for (SundayCart cart : carts) {
                cartType=cart.getCartType();
                if (cart.getSceneId().longValue() == scene.getId()) {
                    SundayCountSceneDto countScene = new SundayCountSceneDto();
                    countScene.setId(scene.getId());
                    countScene.setCartId(cart.getId());
                    countScene.setName(scene.getName());
                    countScene.setImage(resourceHolder.getStringValue("imgRoot")+scene.getImage());
                    countScene.setNum(cart.getNum());
                    countScene.setPrice(cart.getScenePrice());
                    countScene.setViceName(scene.getViceName());
                    countScene.setStandard(scene.getStandard());
                    countScene.setSelected(true);
                    totalAmount += cart.getScenePrice().doubleValue() * cart.getNum();
                    payAmount += cart.getScenePrice().doubleValue() * cart.getNum();
                    totalNumber += cart.getNum();
                    countScenes.add(countScene);
                }
            }
        }
        countDto.setTotalNum(totalNumber);
        countDto.setCartType(cartType);
        countDto.setCarts(carts);
        countDto.setTotalAmount(totalAmount);
        countDto.setPayAmount(payAmount);
        countDto.setScenes(countScenes);
        return countDto;

    }

    /**
     * 购物车生成订单
     *
     * @param carts
     * @param orderId
     */
    public void cartToOrder(List<SundayCart> carts, Long orderId) {
        for (SundayCart cart : carts) {
            cart.setStatus(SundayCommonConstants.YES);
            cart.setOrderId(orderId);
            super.updateExceptEmpty(cart.getId(), cart);
        }


    }

    /**
     * 删除购物车，支持批量删除
     *
     * @param cartIds
     * @param memberId
     * @param cartType
     */
    public void deleteCart(List<Long> cartIds, Long memberId, Integer cartType) {
        Map<String, Object> param = new HashMap<>();
        if (ListUtil.isNotNull(cartIds)) {
            param.put("id in", cartIds);
        }
        param.put("memberId", memberId);
        if (cartType != null) {
            param.put("cartType", cartType);
        }
        super.delete(param);
    }

}
